package org.xiaojl.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xiaojl.modules.sys.entity.SysResource;
import org.xiaojl.modules.sys.entity.SysRoleResource;
import org.xiaojl.modules.sys.mapper.SysResourceMapper;
import org.xiaojl.modules.sys.service.SysResourceService;
import org.xiaojl.modules.sys.service.SysRoleResourceService;
import org.xiaojl.utils.ToolUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Service
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResource> implements SysResourceService {

	@Autowired
	private SysResourceMapper sysResourceMapper;
	@Autowired
	private SysRoleResourceService sysRoleResourceService;
	
	@Override
	public List<SysResource> selectListByRoleIds(String roleIds,String type) {
		List<String> roldIdsList = Arrays.asList(roleIds.split(","));
		return sysResourceMapper.selectListByRoleIds(roldIdsList,type);
	}

	/**
	 * 获取用于编制菜单时的树.
	 */
	@Override
	public String selectAllResourceTree(Long pid) {
		List<SysResource> resourceList = this.selectList(
				new EntityWrapper<SysResource>()
				//.eq("type", "0") //资源类别:0-菜单，1-按钮
				.eq("status", 0) //是否启用
				.orderBy("seq", true)
				);
		StringBuffer strJson = new StringBuffer();
		recursionTreeMenu(pid+"", strJson, resourceList,true);
		return strJson.toString();
	}

	/**
	 * 递归输出树形菜单
	 */
	private void recursionTreeMenu(String pId, StringBuffer buffer, List<SysResource> list, boolean first) {
		if (first) {
			buffer.append("<ul class=\"tree treeFolder expand \" >");
		} else {
			buffer.append("<ul>");
		}
		List<SysResource> listMap = getSonMenuListByPid(pId, list);
		for (SysResource map : listMap) {
			String id = map.getId().toString();// id
			String name = map.getName();// 名称
			String isLeaf = map.getIsLeaf().toString();// 是否叶子科目
			buffer.append("<li><a onclick=\"onClickMenuNode('" + id + "')\" href=\"#\" target=\"ajax\" rel=\"jbsxBox\"  value='" + id + "' id='" + id + "'>" + name + "</a>");
			if (!isLeaf.equals("0")) {
				recursionTreeMenu(id, buffer, list, false);
			}
			buffer.append("</li>");
		}
		buffer.append("</ul>");
	}
	
	/**
	 * 根据(pId)获取(menuList)中的所有子菜单集合.
	 * 
	 * @param pId
	 *            父菜单ID.
	 * @param menuList
	 *            菜单集合.
	 * @return sonMenuList.
	 */
	private List<SysResource> getSonMenuListByPid(String pId, List<SysResource> menuList) {
		List<SysResource> sonMenuList = new ArrayList<SysResource>();
		for (SysResource menu : menuList) {
			if (menu != null) {
				String parentId = menu.getPid()+"";// 父id
				if (parentId.equals(pId)) {
					sonMenuList.add(menu);
				}
			}
		}
		return sonMenuList;
	}

	@Override
	public void insertWithCacade(SysResource resource) {
		if(ToolUtil.isEmpty(resource)){
			return ;
		}
		if(ToolUtil.isNotEmpty(resource.getPid())){
			SysResource p = this.selectById(resource.getPid());
			if(ToolUtil.isNotEmpty(p)){
				if(resource.getType()==1){
					p.setIsLeaf(2);
				}else{
					p.setIsLeaf(1);
				}
				this.updateById(p);
			}
		}
		
		sysResourceMapper.insert(resource);
		
		//默认给管理员角色授权 roleId = 1
		if(ToolUtil.isNotEmpty(resource.getId())){
			SysRoleResource rr = new SysRoleResource();
			rr.setRoleId(1L);
			rr.setResourceId(resource.getId());
			rr.setCreateBy(-1L);
			
			sysRoleResourceService.insert(rr);
		}
		
	}

	@Override
	public void deleteWithCacade(SysResource menu) {
		Long parentId = menu.getPid(); // 获取父菜单ID
		//删除
		this.deleteById(menu.getId());
		
		// 删除菜单后，要判断其父菜单是否还有子菜单，如果没有子菜单了就要将其父菜单设为叶子节点
		List<SysResource> childList = this.selectList(new EntityWrapper<SysResource>().eq("pid", parentId));
		if (childList == null || childList.isEmpty()) {
			// 此时要将父菜单设为叶子
			SysResource parent = this.selectById(parentId);
			parent.setIsLeaf(0);
			this.updateById(parent);
		}
		
		//删除角色资源表
		sysRoleResourceService.delete(new EntityWrapper<SysRoleResource>().eq("resourceId", menu.getId()));
	}
	
}
